package com.unicom.office.templateproc;

import com.unicom.office.dataitem.DataItem;
import com.unicom.office.dataitem.ListDataItem;
import com.unicom.office.dataitem.StringDataItem;
import com.unicom.office.runtime.OfficeRuntime;
import com.unicom.office.templatefunc.AddFunc;
import com.unicom.office.type.CellTypeItem;
import com.unicom.office.type.TypeItem;
import com.unicom.office.unit.CellUnit;
import com.unicom.office.unit.OfficeUnit;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Item2Proc extends TemplateProc {
    public static final Item2Proc INSTANCE = new Item2Proc();

    public void run(OfficeUnit unit, List<Object> params, OfficeRuntime officeRuntime) {
        ListDataItem list = (ListDataItem) params.get(0);
        DataItem i = (DataItem) params.get(1);

        Map<String, String> map = new HashMap<String, String>();
        for (int j = 2; j < params.size() - 1; j++) {
            StringDataItem key = (StringDataItem) params.get(j);
            StringDataItem value = (StringDataItem) params.get(j + 1);
            map.put(key.getValue(), value.getValue());
            j++;
        }

        boolean b = true;
        for (Object item : list.getValue()) {
            Map<String, Object> props = (Map<String, Object>) item;
            b = true;
            for (String key : map.keySet()) {
                if(props.containsKey(key)) {
                    if(!props.get(key).equals(map.get(key))) {
                        b = false;
                        break;
                    }
                }else {
                    b = false;
                    break;
                }
            }
            if(b) {
                officeRuntime.set(i.getConfig(), props);
                return;
            }
        }

        String message = "未找到匹配属性值";
        for (String key : map.keySet()) {
            message += "[" + key + ": " + map.get(key) + "]";
        }
        throw new RuntimeException(message);
    }

    public void runForMatch(OfficeUnit unit, List<Object> params, OfficeRuntime officeRuntime) {

    }

    public String getName() {
        return "item2";
    }

    public TypeItem getType() {
        return CellTypeItem.INSTANCE;
    }
}
